package example;

import com.alibaba.fastjson.JSON;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.HttpRequestHandler;
import example.model.DecryptReq;
import example.model.DecryptResp;
import example.model.EncryptReq;
import example.model.EncryptResp;
import example.service.AppService;
import example.util.APIUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class App implements HttpRequestHandler {

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) throws IOException {

        try {
            // 获取body
            String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
            String requestURL = (String) request.getAttribute("FC_REQUEST_PATH");
            if (requestURL.startsWith("/encrypt")) { // 加密

                // 解析数据
                EncryptReq encryptReq = JSON.parseObject(body, EncryptReq.class);
                if (StringUtils.isBlank(encryptReq.getKey())) {
                    APIUtil.fail(response, "key不存在");
                    return;
                }

                if (StringUtils.isBlank(encryptReq.getValue())) {
                    APIUtil.fail(response, "value不存在");
                    return;
                }

                EncryptResp resp = AppService.encrypt(encryptReq);
                resp.setData(encryptReq.getValue());
                APIUtil.ok(response, resp);
            } else if (requestURL.startsWith("/decrypt")) { // 解密
                // 解析数据
                DecryptReq decryptReq = JSON.parseObject(body, DecryptReq.class);
                if (StringUtils.isBlank(decryptReq.getDecryptMsg())) {
                    APIUtil.fail(response, "decryptMsg不存在");
                    return;
                }

                // 获取数据并返回
                String msg = AppService.decrypt(decryptReq.getDecryptMsg());
                DecryptResp resp = new DecryptResp();
                resp.setMsg(msg);
                APIUtil.ok(response, resp);

            } else {
                APIUtil.fail(response, "路由不存在");
            }
        } catch (Exception e) {
            APIUtil.error(response, e.getMessage());
        }
    }
}
